<template>
    <div class="login-container">
        <!-- 首页按钮 -->
        <el-button icon="ArrowLeft" circle class="home-button" @click="goToHome" />

        <el-card class="login-card" shadow="hover">
            <h2>欢迎回来</h2>

            <!-- 登录方式切换 -->
            <el-tabs v-model="activeTab" stretch>
                <el-tab-pane label="账号登录" name="account"></el-tab-pane>
                <el-tab-pane label="邮箱登录" name="emailCode"></el-tab-pane>
            </el-tabs>

            <el-form :model="form" :rules="rules" ref="formRef" label-position="left" label-width="80px"
                @submit.prevent="login">
                <!-- 账号密码登录 -->
                <div v-show="activeTab === 'account'">
                    <el-form-item label="账号" prop="username">
                        <el-input v-model="form.username" placeholder="请输入账号" />
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="form.password" placeholder="请输入密码" type="password" show-password />
                    </el-form-item>

                    <!-- 忘记密码 -->
                    <div class="forget-tip">
                        <span @click="goToForget">忘记密码？</span>
                    </div>
                </div>

                <!-- 邮箱验证码登录 -->
                <div v-show="activeTab === 'emailCode'">
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="form.email" placeholder="请输入邮箱" />
                    </el-form-item>
                    <el-form-item label="验证码" prop="code">
                        <el-input v-model="form.code" placeholder="请输入验证码" style="width: 60%" />
                        <el-button type="primary" plain style="margin-left: 10px" :disabled="!!countdown"
                            @click="sendEmailCode">
                            {{ countdown ? `${countdown}s后重发` : '获取验证码' }}
                        </el-button>
                    </el-form-item>
                </div>

                <el-button native-type="submit" type="primary" class="submit-btn" :loading="loading">
                    登录
                </el-button>

                <!-- 注册提示 -->
                <div class="register-tip">
                    没有账号？
                    <span @click="goToRegister">立即注册</span>
                </div>
            </el-form>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import * as loginApi from '@/api/login';
import { user } from '@/stores/user.js';
import { ElMessage } from 'element-plus';

const router = useRouter();
const userStore = user();

// 当前激活的登录方式
const activeTab = ref('account');
const loading = ref(false);
const formRef = ref(null);

// 倒计时（验证码）
const countdown = ref(0);

// 表单数据（两个模式共用，但字段不冲突）
const form = reactive({
    username: '',
    password: '',
    email: '',
    code: ''
});

// 校验规则
const rules = {
    username: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 5, max: 20, message: '账号长度应在 5 到 20 个字符之间', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 32, message: '密码长度应在 6 到 32 个字符之间', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    code: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { pattern: /^\d{6}$/, message: '验证码必须为 6 位数字', trigger: 'blur' }
    ]
};

// 发送邮箱验证码（带倒计时）
const sendEmailCode = async () => {
    if (!form.email) {
        ElMessage.error('请先输入邮箱');
        return;
    }

    // 仅校验邮箱字段
    try {
        await formRef.value.validateField('email');
    } catch {
        return;
    }

    if (countdown.value > 0) return; // 防止重复点击

    try {
        const res = await loginApi.sendEmailCode(form.email);
        if (res.success) {
            ElMessage.success('验证码已发送，请注意查收');
            startCountdown(60);
        } else {
            ElMessage.error(res.message || '发送验证码失败，请稍后再试');
        }
    } catch (err) {
        console.error('发送验证码失败:', err);
        ElMessage.error('发送失败，请检查网络');
    }
};

// 启动倒计时
const startCountdown = (seconds) => {
    countdown.value = seconds;
    const timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
            clearInterval(timer);
        }
    }, 1000);
};

// 登录逻辑（只校验当前 tab 的字段）
const login = async () => {
    try {
        // 清除之前所有错误状态
        await formRef.value?.clearValidate();

        let valid = false;
        if (activeTab.value === 'account') {
            // 只校验账号和密码
            valid = await formRef.value?.validateField(['username', 'password'], (errors) => !errors).catch(() => false);
        } else {
            // 只校验邮箱和验证码
            valid = await formRef.value?.validateField(['email', 'code'], (errors) => !errors).catch(() => false);
        }

        if (!valid) {
            ElMessage.error('请检查表单填写');
            return;
        }

        loading.value = true;

        try {
            let res;
            if (activeTab.value === 'account') {
                res = await loginApi.loginWithPassword({
                    username: form.username,
                    password: form.password
                });
            } else {
                res = await loginApi.loginWithEmailCode({
                    email: form.email,
                    code: form.code
                });
            }
            console.debug(res);
            if (res.code === 100) {
                userStore.setToken(res.data.token);
                userStore.setUserInfo(res.data);
                localStorage.setItem('token', res.data.token);
                ElMessage.success('登录成功');
                console.debug(res.data.roleId);
                // 根据角色ID跳转到不同页面
                // 角色ID为1：普通用户，跳转到普通用户页面
                // 角色ID为2：管理员，跳转到管理员页面
                if (res.data.roleId === 1) {
                    router.push('/home');
                } else if (res.data.roleId === 2) {
                    console.debug('管理员登录');
                    router.push('/admin/home');
                } else {
                    router.push('/home');
                }
            } else {
                ElMessage.error(res.message || '登录失败');
            }
        } catch (err) {
            console.error('登录请求失败:', err);
            ElMessage.error('登录失败，请检查网络或输入信息');
        }
    } catch (err) {
        console.error('表单验证异常:', err);
    } finally {
        loading.value = false;
    }
};

// 页面跳转
const goToRegister = () => {
    router.push('/auth/register');
};

const goToForget = () => {
    router.push('/forget');
};

const goToHome = () => {
    router.push('/home');
};
</script>

<style lang="scss" scoped>
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    position: relative;

    .home-button {
        position: absolute;
        top: 20px;
        right: 20px;
        z-index: 10;
        background-color: white;
        border: 1px solid #ddd;
        color: #333;

        &:hover {
            background-color: #f0f0f0;
        }
    }

    .login-card {
        width: 100%;
        max-width: 420px;
        padding: 2rem;
        border-radius: 12px;
        background-color: #ffffffee;

        h2 {
            margin-bottom: 1.5rem;
            font-weight: 600;
            color: #333;
            text-align: center;
        }

        .submit-btn {
            width: 100%;
            margin-top: 1rem;
        }

        .register-tip,
        .forget-tip {
            margin-top: 0.8rem;
            font-size: 0.9rem;
            color: #666;
            text-align: center;

            span {
                color: #4f8cf2;
                cursor: pointer;
                margin-left: 4px;

                &:hover {
                    text-decoration: underline;
                }
            }
        }

        .forget-tip {
            text-align: right;
            margin-top: -0.5rem;
            margin-bottom: 1rem;
        }
    }
}
</style>